package com.lims.模拟测试工具;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.util.Map;
import java.util.UUID;

import okhttp3.*;

/**
 * @author limaosheng
 * @create 2021-08-16 11:02
 * @desc 测试工具类
 */
public class HttpUtils {

    //时间字段转成json字符串需要指定格式
    static JSONConfig jsonConfig = JSONConfig.create().setDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * url包含http，则不获取host
     */
    public static JSONObject post(String url, Object object){
        String param = "";
        String aesKey = "";
        if(object != null){
            if(object instanceof String){
                param = (String) object;
            }else {
                param = JSONUtil.toJsonStr(object,jsonConfig);
            }
        }
        if(!url.startsWith("http")){
            url = 域名.getHost(url) + url;
        }
        //RSA+AES加密入参
        if(url.contains("/rsa/aes")){
            aesKey = AESUtil.generateRandomKey();
            param = AESUtil.encrypt(param,aesKey);
            aesKey = RSAUtil.encryptFront(aesKey);
        }
        return doPostStr(url,param,aesKey);
    }

    public static JSONObject doPostStr(String url, String param,String aesKey){
        JSONObject jsonObject = null;
        try {
            System.out.println("请求地址:" + url);
            System.out.println("参数json字符串:" + param);
            if(url.contains("/rsa/aes")) {
                System.out.println("参数原文：" + AESUtil.decrypt(param,RSAUtil.decryptFront(aesKey)));
                System.out.println("AES密钥：" + RSAUtil.decryptFront(aesKey));
                System.out.println("RSA加密后：" + aesKey);
                AesReq aesReq = new AesReq();
                aesReq.setData(param);
                aesReq.setKey(aesKey);
                param = JSONUtil.toJsonStr(aesReq,jsonConfig);
            }
            //请求，重写verify避过证书校验
            OkHttpClient client = new OkHttpClient().newBuilder().hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            }).build();
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param);
            HttpUrl httpUrl = HttpUrl.parse(url);
            HttpUrl.Builder urlBuilder = httpUrl.newBuilder();
            urlBuilder.addQueryParameter("d", "31112043");
            Request request;
                request = new Request.Builder()
                        .addHeader("Content-Type", "application/json; charset=utf-8")
                        .addHeader("traceId", UUID.randomUUID().toString())
                        .addHeader("mobile",LoginMsg.MOBILE)
                        .addHeader("communityId",LoginMsg.COMMUNITY_ID)
                        .url(urlBuilder.build()).post(body).build();
            //响应
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            System.out.println("请求结果：");
            System.out.println(FormatToJson.formatToJson(result));
            jsonObject = JSON.parseObject(result);
            //解密后
            if(url.contains("/rsa/aes")) {
                String data = jsonObject.getString("data");
                if(data != null){
                    String aesKeyRsa = jsonObject.getString("aesKey");
                    System.out.println("返回的AES密钥：" + aesKeyRsa);
                    System.out.println("AES密钥RSA解密后：" + RSAUtil.decrypt(aesKeyRsa));
                    System.out.println("AES解密后的结果：" + FormatToJson.formatToJson(AESUtil.decrypt(data,RSAUtil.decrypt(aesKeyRsa))));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    public static void doGet(String url){
        try {
            if(!url.startsWith("http")){
                url = 域名.getHost(url) + url;
            }
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .addHeader("traceId", UUID.randomUUID().toString())
                    .addHeader("mobile",LoginMsg.MOBILE)
                    .addHeader("communityId",LoginMsg.COMMUNITY_ID)
                    .url(url).get().build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            System.out.println("请求地址:" + url);
            System.out.println("请求结果：");
            System.out.println(FormatToJson.formatToJson(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String doPostFile(String url,Map<String,Object> param){
        if(!url.startsWith("http")){
            url = 域名.getHost(url) + url;
        }
        HttpResponse httpResponse = HttpRequest.post(url)
                .contentType(ContentType.MULTIPART.getValue())
                .form(param)
                .header("traceId", UUID.randomUUID().toString())
                .header("mobile",LoginMsg.MOBILE)
                .header("communityId",LoginMsg.COMMUNITY_ID)
                .execute();
        String res = httpResponse.body();
        System.out.println("请求地址:" + url);
        System.out.println("请求结果：");
        System.out.println(FormatToJson.formatToJson(res));
        return res;
    }
}
